<template>
  <div class="shop-product">
    <ShopInfoBar
      v-if="shopDetail"
      :container-class="['shop-info']"
      :cover="shopDetail.cover"
      :name="shopDetail.name"
      :tag="shopDetail.tag"
      :is-photography="shopDetail.is_photography"
      :good="shopDetail.goods_number"
      :pkg="shopDetail.package_number"
      :visitor-number="shopDetail.visitor"
      :phone="shopDetail.phone"
      @click="onClickShop"
    />

    <Banner :banners="shopBanner" v-if="shopBanner && shopBanner.length" />
    <div class="placehold-box" v-if="!shopBanner || shopBanner.length === 0"></div>

    <!-- <van-search v-model="name" placeholder="点击输入搜索" /> -->

    <!-- 筛选 -->
    <div class="box_flex">
      <!-- 搜索 -->
      <van-search v-model="name" style="width: 82%;" placeholder="商品名/品牌/商品种类/关键字" />
      <!-- 筛选 -->
      <div class="select-wrap">
        <!-- <selectBoxNew @sort="onChangeSort" @range="onChangeRange" /> -->
        <span
          class="shop-category__filter-type"
          style="padding:10rpx 0rpx;"
          @click="showFilter = true"
        >
          <span class="icon">&#xe876;</span> 筛选
        </span>
      </div>
    </div>
    <!-- 排序 -->
    <SelectSort @sort="onChangeSort" />
    <!-- <div class="shop-product__filter text-small">
            <wx-picker class="shop-product__filter-type" :range="sortOptions" range-key="text" :value="sortIndex" mode="selector" @change="onChangeSort" @cancel="onCancelSort">
                <div class="select" :class="{ 'primary-color bor-bottom': selectType === 'sort'}">
                    <span class="text">{{sortName ? sortName : '排序'}}</span>
                    <span class="icon" :class="{ 'invert primary-color': selectType === 'sort'}">&#xeb6d;</span>
                </div>
            </wx-picker>
            <span class="shop-product__filter-type" @click="showFilter = true">
                <span class="icon">&#xe876;</span> 筛选
            </span>
            <- <SelectBox @sort="onChangeSort" @range="onChangeRange" /> -
    </div>-->
    <!-- <SelectBox @sort="onChangeSort" @range="onChangeRange" /> -->

    <!-- 商品列表 -->
    <div v-if="shopDetail && list.length > 0" class="goods-box">
      <div class="good clearfix">
        <ProductListItem
          v-for="(product, index) in list"
          :key="index"
          :cover="product.list_cover ? product.list_cover : product.cover"
          :name="product.name"
          :tag="product.tag"
          :shop-tag="shopDetail.tag"
          :price="product.price"
          :display-price="product.display_price"
          :read-number="product.visitor || 0"
          :share-number="product.share_number || 0"
          @click="onClickProduct(product)"
        ></ProductListItem>
      </div>
    </div>

    <ListEmpty v-if="list.length === 0" />

    <!-- 过滤器 -->
    <div v-if="showFilter" class="popup-container .filter-popup" @click="showFilter = false">
      <div class="popup popup--pos-right" @click.stop>
        <div class="filter-popup__title">价格区间</div>
        <div class="filter-popup__input-wrap">
          <input
            type="number"
            v-model="tempFilter.min"
            placeholder="最低价"
            class="filter-popup__input"
          />
          <span class="filter-popup__line">&nbsp;——&nbsp;</span>
          <input
            type="number"
            v-model="tempFilter.max"
            placeholder="最高价"
            class="filter-popup__input"
          />
        </div>
        <!--  getParams22 -->
        <template v-for="(item,index) in getParams ">
          <!-- 一级分类 -->
            <template v-if="item.field == 'first_category_id'">
                <div class="filter-popup__title" :key="index">{{item.title}}</div>
                <div class="filter-popup_params" :key="index">
                    <template v-for="(row, rowIndex) in item.data" >
                        <div class="filter-popup_params_item" :key="rowIndex" :class="{'filter-popup__item--active': row.id === tempFilter.first_category_id}" @click="onClickfirst_category_id(row)">{{row.name}}</div>
                    </template>
                </div>
            </template>
            <!-- 规格 -->
            <template v-if="item.field == 'category_id'">
                <div class="filter-popup__title" :key="index">{{item.title}}</div>
                <div class="filter-popup_params" :key="index">
                    <template v-for="(row4, rowIndex4) in item.data" >
                        <template v-if="tempFilter.first_category_id == null">
                            <div class="filter-popup_params_item" :key="rowIndex4" :class="{'filter-popup__item--active': row4.name === tempFilter.SpecName}" @click="onClickCategory(row4)">{{row4.name}}</div>
                        </template>
                        <template v-else>
                            <template v-if="row4.flag && tempFilter.first_category_id != null">
                                <div class="filter-popup_params_item" :key="rowIndex4" :class="{'filter-popup__item--active': row4.name === tempFilter.SpecName}" @click="onClickCategory(row4)">{{row4.name}}</div>
                            </template>
                            <!-- 不可选的 -->
                            <template v-else>
                                <div class="filter-popup_params_item" :key="rowIndex4" style="color:#999;background-color:#e0e0e0;" >{{row4.name}}</div>
                            </template>
                        </template>
                        
                        <!-- <div class="filter-popup_params_item" :key="rowIndex" :class="{'filter-popup__item--active': row.id === tempFilter.category}" @click="onClickCategory(row)">{{row.name}}</div> -->
                    
                    </template>
                </div>
            </template>
            <!-- 品牌 -->
            <template v-if="item.field == 'brand_id'">
                <div class="filter-popup__title" :key="index">{{item.title}}</div>
                <div class="filter-popup_params" :key="index">
                    <template v-for="(row, rowIndex) in item.data" >
                        <div class="filter-popup_params_item" :key="rowIndex" :class="{'filter-popup__item--active': row.name === tempFilter.brand}" @click="onClickBrand(row)">{{row.name}}</div>
                    </template>
                </div>
            </template>
        </template>
        <div class="filter-popup__btn">
          <div
            @click="onClickSelectReset"
            class="btn btn-mobile btn-normal btn-white-red red-border"
          >重置</div>
          <div @click="onClickSelectConfirm" class="btn btn-mobile btn-normal btn-red">确定</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { api } from "@/lib/api";
import store from "@/store";
import Banner from "@/components/common/banner.vue";
import ShopInfoBar from "@/features/shop/infoBar.vue";
import ProductListItem from "@/features/product/listItem.vue";
import SelectBox from "@/features/shop/selectBox.vue";
import ListEmpty from "@/components/list/listEmpty.vue";

import SelectSort from "@/features/shop/selectSort.vue";

import { Component, Vue, Watch } from "vue-property-decorator";
import { EMPTY_LIST, ROUTE_NAME } from "@/lib/constant";
import { WatchDelay } from "@/lib/utils";
import { Route } from "vue-router";

Component.registerHooks(["beforeRouteEnter"]);

@Component({
  name: "ShopProduct",
  components: {
    Banner,
    ShopInfoBar,
    ProductListItem,
    SelectBox,
    ListEmpty,
    SelectSort
  }
})
export default class ShopProduct extends Vue {

  /** 页面标题 */
  public title = "";
  public sortValue = "";
  public sortName = "";
  /** 根据名字搜索 */
  public name = "";
  /** 排序选项 */
  public sortOptions: ValueText[] = [
    { value: "multiple", text: "综合排序" },
    { value: "createdAt", text: "新上架" },
    { value: "priceDesc", text: "价格由高到低" },
    { value: "priceAsc", text: "价格由低到高" },
    { value: "visitor", text: "高人气" }
  ];
  /** 是否显示filter */
  public showFilter = false;
  public filter: {
    min: string;
    max: string;
    category: number;
    brand: string;
    SpecName: string,
    first_category_id:number | null;
  } = {
    /** 最低价格，单位: 分 */
    min: "",
    /** 最高价格，单位: 分 */
    max: "",
    category: -1,
    brand: '',
    SpecName: '',
    first_category_id:null
  };
  public tempFilter: {
    min: string;
    max: string;
    category: number;
    brand: string;
    SpecName: string;
    first_category_id:number | null;
  } = {
    min: "",
    max: "",
    category: -1,
    brand: '',
    SpecName: '',
    first_category_id:null
  };
  // 顶级分类id
    public topCategoryId: any = '';

  /** 用户基础信息 */
  public get userBasicInfo() {
      return store.state.user.basicInfo;
  }
  /** 店铺id */
  public get shopId() {
    return this.$route.params.shopId;
  }
  /** 门店详情 */
  public get shopDetailMap() {
    return store.state.shop.shopDetailMap;
  }

  /** banners */
  public get bannersMap() {
    return store.state.shop.banners;
  }

  /** 商品列表 */
  public get listsMap() {
    return store.state.good.lists;
  }
  /** 店铺详情 */
  public get shopDetail() {
    return this.shopDetailMap[Number(this.shopId)] || null;
  }
  public get type() {
    return this.shopDetail && this.shopDetail.category
      ? this.shopDetail.category[0]
      : null;
  }

  /** 店铺banner */
  public get shopBanner() {
    return this.bannersMap[this.shopId] || null;
  }

  /** 区间是否有效 */
  public get isScreenValid() {
    if (this.filter.min && this.filter.max) {
      const low = Number(this.filter.min);
      const high = Number(this.filter.max);
      return !isNaN(low) && !isNaN(high) && high > low;
    }
    return true;
  }

  /** 价格区间 */
  public get screen() {
    return this.isScreenValid
      ? {
          min: this.filter.min ? Number(this.filter.min) * 100 : "",
          max: this.filter.max ? Number(this.filter.max) * 100 : ""
        }
      : null;
  }
  /** 商品列表 */
  public get lists() {
    // const key = `${this.filter.brand}_${this.shopId}_${this.title}_${
    //   this.filter.category >= 0 ? this.filter.category : null
    // }_${this.filter.first_category_id}_${this.sortValue}_${JSON.stringify(this.screen)}_${this.name}`;
    const key = `${this.filter.brand}_${this.shopId}__${
      this.filter.SpecName
    }_${this.filter.first_category_id}_${this.sortValue}_${JSON.stringify(this.screen)}_${this.name}`;
    return this.listsMap[key] || EMPTY_LIST;
  }

  /** 商品列表 */
  public get list() {
    const map = store.state.good.listsMap;
    return this.lists.list.map(id => map[id]);
  }
  public get sortIndex() {
    return this.sortOptions.map(option => option.value).indexOf(this.sortValue);
  }
  /** 二级类别信息 */
  public get category() {
    const list = store.state.shop.category[this.type] || [];
    const result: IdName[][] = [];
    for (let i = 0, len = list.length; i < len; i = i + 3) {
      const row: IdName[] = [];
      if (list[i]) {
        row.push(list[i]);
      }
      if (list[i + 1]) {
        row.push(list[i + 1]);
      }
      if (list[i + 2]) {
        row.push(list[i + 2]);
      }
      result.push(row);
    }
    return result;
  }
  /** 品牌列表 */
  public get brand() {
    const list = store.state.good.brand[this.shopDetail.type] || [];
    // const result: IdName[][] = [];

    // for (let i = 0, len = list.length; i < len; i = i + 3) {
    //   const row: IdName[] = [];
    //   if (list[i]) {
    //     row.push(list[i]);
    //   }
    //   if (list[i + 1]) {
    //     row.push(list[i + 1]);
    //   }
    //   if (list[i + 2]) {
    //     row.push(list[i + 2]);
    //   }
    //   result.push(row);
    // }
    // return result;
    return list;
  }

  @WatchDelay("name", 500)
  @Watch("name")
  public onName() {
    this.getProductList(true,true);
  }

  /** 获取筛选内容 */
  public get getParams() {
    this.topCategoryId = store.state.good.getParams[0].top_category_id;
    this.title = store.state.good.getParams[0].title;
    return store.state.good.getParams;
  }

  /**
   * 修改sort
   */
  public onChangeSort(e: any) {
    // const option = this.sortOptions[e.detail.value];
    // if (option) {
    //     this.sortValue = option.value;
    //     this.sortName = option.text;
    // }

    this.sortValue = e.val;
    this.sortName = e.name;
    this.getProductList(true,true);
    this.onCancelSort();
  }
  public onCancelSort() {
    // this.selectType = '';
  }

    //   点击以及分类
    public onClickfirst_category_id(category: IdName){
        this.tempFilter.first_category_id = category.id;
        this.tempFilter.SpecName = '';
         // 获取一级分类下的规格
        this.getFirstCategorySpec();
    }
    // 获取一级分类下的规格
    public getFirstCategorySpec(){
        return store.dispatch('good/getShopFirstCategorySpec', {
            top_category_id: this.topCategoryId,
            first_category_id: this.tempFilter.first_category_id
        });
    }
  /**
   * 点击类别
   */
  public onClickCategory(category: IdName) {
    this.tempFilter.category = category.id;
    this.tempFilter.SpecName = category.name;
  }
  /**
   * 点击品牌
   */
  public onClickBrand(brand: IdName) {
    this.tempFilter.brand = brand.name;
  }
  /**
   * 确认
   */
  public onClickSelectConfirm() {
    const { filter, tempFilter } = this;
    filter.min = tempFilter.min;
    filter.max = tempFilter.max;
    filter.category = tempFilter.category;
    filter.brand = tempFilter.brand;
    filter.first_category_id = tempFilter.first_category_id;
    filter.SpecName = tempFilter.SpecName;
    this.showFilter = false;
    this.getProductList(true,true);
  }
  public onClickSelectReset() {
    const temp = this.tempFilter;
    temp.min = "";
    temp.max = "";
    temp.category = -1;
    temp.brand = '';
    temp.first_category_id = null;
    temp.SpecName = '';
    this.filter = {
      min: "",
      /** 最高价格，单位: 分 */
      max: "",
      category: -1,
      brand: '',
      SpecName: '',
      first_category_id:null
    }

    this.sortName = '';
    this.sortValue = '';
    this.name = '';
  }
  /**
   * 更新价格范围
   */
  // public onChangeRange(range: any) {
  //     this.min = range.min;
  //     this.max = range.max;
  //     this.getProductList();
  // }

  /**
   * 点击product
   */
  public onClickProduct(product: any) {
    // api.navigateTo({
    //     url: '/pages/product_detail/main',
    //     query: {
    //         product_id: product.id,
    //     },
    // });

    api.push({
      name: ROUTE_NAME.PRODUCT_DETAIL,
      params: {
        productId: product.id
      }
    });
  }

  /**
   * 获取商品列表
   */
  public getProductList(forceUpdate = false, switchState) {
    return store.dispatch("good/getlists", {
      brand: this.filter.brand,
      shopId: this.shopId,
      category: this.title? this.title : '',
      SpecName: this.filter.SpecName,
      // categoryId: this.filter.category >= 0 ? this.filter.category : null,
      first_category_id:this.filter.first_category_id,
      offset: switchState?0:this.list.length,
      count: 10,
      sort: this.sortValue,
      screen: this.screen,
      name: this.name,
      forceUpdate
    });
  }
  public onReachBottom() {
    this.getProductList(false,false);
  }

  // public async beforeRouteEnter(to: Route, from: Route, next: any) {
  //   store.commit("startRequest");
  //   await store.dispatch("shop/getShopDetail", {
  //     shopId: to.params.shopId
  //   });
  //   store.commit("endRequest");
  //   next();
  // }
  // 
  public async beforeRouteEnter(to: Route, from: Route, next: any) {
      const shopId = to.params.shopId;
      await Promise.all([
          store.dispatch('utils/getPageConfig'),
      ]);
      next();
  }
  // 
  public async created() {
    store.commit("utils/startRequest");
    await store.dispatch("shop/getShopDetail", {
      shopId: this.shopId
    });
    wx.setNavigationBarTitle({
        title: this.shopDetail.name,
    });

    await Promise.all([
      this.getProductList(true,true),
      this.type
        ? store.dispatch("shop/getCategory", { type: this.type })
        : null,
      store.dispatch("shop/getBanners", {
        shopId: this.shopId
      })
    ]);
    store.commit("utils/endRequest");

    store.dispatch("good/getBrand", {
      parent: this.shopDetail.type
    });
    store.dispatch("good/getParams", {
      shop_id: this.shopId
    });

    // 新增分享
    window.onShareAppMessage = (data) => {
        // return {
        //     title: this.shopDetail.name,
        //     imageUrl: '',
        //     path: `/pages/SHOP_PRODUCT/main?shop_id=${this.shopId}&referrer_id=${this.userBasicInfo.id}`,
        // };

        const url = this.$router.resolve({
            name: ROUTE_NAME.SHOP_PRODUCT,
            params: {
                shopId: this.shopId,
            },
            query: {
                referrer: this.userBasicInfo.id + '',
            },
        }).route.fullPath;

        return {
            title: this.shopDetail.name,
            imageUrl: '',
            // path: `/pages/index/main?referrer_id=${this.userBasicInfo.id}`,
            miniprogramPath: `/pages/main/index?type=share&targeturl=${encodeURIComponent(url)}`, // 如果需要分享原始小程序页面路由，可传递此参数
        };
    };


    window.addEventListener("reachbottom", this.onReachBottom);
  }
  public beforeDestroy() {
    window.removeEventListener("reachbottom", this.onReachBottom);
  }
}
</script>

<style lang="less">
@import "../../lib/style/mixins.less";

.filter-popup_params {
  display: flex;
  flex-wrap: wrap;
  justify-content: end;
}
.filter-popup_params_item{
    display: inline-block;
    width: 140rpx;
    padding: 16rpx 8rpx;
    font-size: 24rpx;
    line-height: 34rpx;
    background-color: #f5f5f5;
    border-radius: 20rpx;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
    margin: 16rpx 3%;
}

.shop-product {
  .shop-info {
    padding: 10px 35px 0;
    color: @color-white;
    background-color: @color-primary;
    border-bottom-width: 0;
  }
  .placehold-box {
    height: 40rpx;
    margin-bottom: 10px;
    background-color: @color-primary;
  }
  .goods-box {
    padding: 0 36rpx 10px;
    .good {
      margin-right: -26rpx;
    }
  }

  &__filter {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .text-normal();
    &-type {
      padding: 10px 15px;
      .text-normal();
    }
  }
  .box_flex {
    display: flex;
  }
  .select-wrap {
    padding-top: 36rpx;
  }
}
</style>
